package top.jojoace.GlobalExceptionAdvice_And_AutoURI.core;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import top.jojoace.GlobalExceptionAdvice_And_AutoURI.Exception.http.HttpException;
import top.jojoace.GlobalExceptionAdvice_And_AutoURI.core.configuration.ExceptionCodeConfiguration;

import javax.servlet.http.HttpServletRequest;

/**
 * <h1>
 * 过滤所有异常
 * </h1>
 *
 * @author a1615
 */
@ControllerAdvice
public class GlobalExceptionAdvice {

    @Autowired
    private ExceptionCodeConfiguration codeConfiguration;


    /**
     * <h1>@ControllerAdvice 控制器消息类</h1>
     * <h2>@ExceptionHandler(value = XXXXXException.class) 异常处理</h2>
     * <p>处理从控制器抛出的 XXXXXException 异常</p><br><br><br><br><br><br>
     *
     *
     * <h1>注解设置状态码</h1>
     * <h2>@ResponseStatus(code = HttpStatus.XXX) 设置响应状态码</h2>
     */
    @ResponseBody
    @ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR)//500
    @ExceptionHandler(value = Exception.class)      //拦截所有异常,处理未知异常
    public UnifyResponse handleException(HttpServletRequest request, Exception e) {
        System.out.println("catch any Exception...");
        e.printStackTrace();
        UnifyResponse message = new UnifyResponse(
                9999,
                "服务器异常",
                request.getMethod() + " " + request.getRequestURI());
        return message;
    }


    /**
     * <h1>手动设置HttpStatus</h1>
     * <h2>return ResponseEntity</h2>
     * <h3>new ResponseEntity<响应体Body类型>(响应体Body,HttpHeaders响应头,httpStatus状态码);</h3>
     *
     */
    @ExceptionHandler(value = HttpException.class)      //处理已知异常
    public ResponseEntity HandlerHttpException(HttpServletRequest request, HttpException exception) {
        System.out.println("catch any HttpException...");

        System.out.println(this.codeConfiguration.getMessage(exception.getCode()));

        UnifyResponse message = new UnifyResponse(
                exception.getCode(),
                this.codeConfiguration.getMessage(exception.getCode()),
                request.getMethod() + " " + request.getRequestURI()
        );

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);//响应头媒体类型
        HttpStatus httpStatus = HttpStatus.resolve(exception.getHttpStatusCode());//响应状态码

        ResponseEntity<UnifyResponse> r = new ResponseEntity<UnifyResponse>(message,httpHeaders,httpStatus);

        return r;
    }
}
